﻿using GalaSoft.MvvmLight.Command;
using HandyControl.Data;
using LogModule.Interface;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using StaffModule.DbContexts;
using StaffModule.Models;
using StaffModule.Utils;
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using MessageBox = System.Windows.MessageBox;

namespace StaffModule.ViewModels {

    public class StaffViewModel : BindableBase {
        //日志
        private readonly ILogService Logger;
        //数据库上下文
        private readonly StaffDbContext StaffDbContext;
        // 对话框服务
        private readonly IDialogService DialogService;
        //构造函数
        public StaffViewModel(ILogService logger, StaffDbContext staffDbContext, IDialogService dialogService) {
            Logger = logger;
            Logger.Info("员工模块初始化");
            #region 初始化
            //对话框服务,在构造函数实例化
            DialogService = dialogService;
            //数据库上下文
            StaffDbContext = staffDbContext;
            //员工表的总表和分页表
            SummaryTable = new ObservableCollection<StaffDetails>();
            CurrentDataList = new ObservableCollection<StaffDetails>();
            //命令绑定方法
            AddStaffCmd = new DelegateCommand(AddStaff);
            RefreshStaffCmd = new DelegateCommand(RefreshStaff);
            SearchByName = new DelegateCommand<string>(SearchByNameFunc);
            SearchByEmployeeId = new DelegateCommand<string>(SearchByEmployeeIdFunc);
            SearchByPhone = new DelegateCommand<string>(SearchByPhoneFunc);
            UpdateStaffCmd = new DelegateCommand<int?>(UpdateStaff);
            DeleteStaffCmd = new DelegateCommand<int?>(DeleteStaff);
            ExportCmd = new AsyncDelegateCommand(Export);

            #endregion

            //刷新员工数据表
            RefreshStaff();

        }

        private void SearchByPhoneFunc(string obj) {
            CurrentDataList = StaffDbContext.StaffDetails.Where(x => x.Phone == obj).ToList().ToObservableCollection();
        }

        private void SearchByEmployeeIdFunc(string obj) {
            CurrentDataList = StaffDbContext.StaffDetails.Where(x => x.EmployeeId == obj).ToList().ToObservableCollection();
        }

        private void SearchByNameFunc(string obj) {
            CurrentDataList = StaffDbContext.StaffDetails.Where(x => x.Name == obj).ToList().ToObservableCollection();
        }

        /// <summary>
        /// 刷新列表
        /// </summary>
        /// <returns></returns>
        private  void RefreshStaff() {
            Task.Run(() => {
                Logger.Info("属性员工列表");
                   // 通过Dispatcher更新UI
                   Application.Current.Dispatcher.BeginInvoke(() => {
                       // 清空现有数据避免重复
                       SummaryTable.Clear();
                       CurrentDataList.Clear();
                       //更新数据总数
                       var query = StaffDbContext.StaffDetails.AsNoTracking().OrderBy(x => x.Id).ToList();
                       SummaryTable = new ObservableCollection<StaffDetails>(query);

                       // 计算最大页码（含边界保护）
                       MaxPageCount = SummaryTable.Count == 0 ? 1 : Math.Max(1, (int)Math.Ceiling((double)SummaryTable.Count / PageSize));

                       // 校正当前页码（防止越界）
                       PageIndex = Math.Min(PageIndex, MaxPageCount);

                       // 加载当前页数据（使用分页公式）
                       LoadCurrentPageData();
                   });
                   }
               );
        }

        // 新增分页数据加载方法
        private void LoadCurrentPageData() {
            int startIndex = (PageIndex - 1) * PageSize;
            var pageData = SummaryTable.Skip(startIndex).Take(PageSize).ToList();
            CurrentDataList = new ObservableCollection<StaffDetails>(pageData);
        }

        // 页码变更处理
        private void PageUpdated(FunctionEventArgs<int> info) {
            PageIndex = info.Info; // 更新当前页码
            LoadCurrentPageData(); // 重新加载数据
        }

        #region 命令
        public DelegateCommand<string> SearchByName { get; set; }
        public DelegateCommand<string> SearchByEmployeeId { get; set; }
        public DelegateCommand<string> SearchByPhone { get; set; }

        public DelegateCommand AddStaffCmd { get; set; }

        public DelegateCommand RefreshStaffCmd { get; set; }

        public DelegateCommand<int?> UpdateStaffCmd { get; set; }

        public DelegateCommand<int?> DeleteStaffCmd { get; set; }

        //public DelegateCommand ExportCmd { get; set; }
        public AsyncDelegateCommand ExportCmd { get; set; }

        //页码改变命令
        public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd => new(PageUpdated);
        //删除员工
        private void DeleteStaff(int? id) {
            if (id == null) {
                return;
            } else {//id不为空
                try {
                    //只根据id没删掉
                    //var temp = new StaffDetails() { Id = (int)id };
                    //--------直接搜出来,浪费性能
                    var temp = StaffDbContext.StaffDetails.Where(x => x.Id == id).ToList()[0];
                    if (temp == null) return;
                    //--------
                    StaffDbContext.StaffDetails.Remove(temp);
                    StaffDbContext.SaveChangesAsync();
                    // 删除后检查：如果是最后一页的唯一项
                    if (CurrentDataList.Count == 1 && PageIndex > 1) {
                        PageIndex--; // 自动返回前一页
                    }
                    Application.Current.Dispatcher.BeginInvoke(RefreshStaff);

                } catch (Exception ex) {
                    Console.WriteLine(ex.Message.ToString());
                }
            }
        }
        //导出
        private async Task Export() {
            try {
                await ExportExcel("d:\\test.xlsx");
               
            } catch (Exception ex) {
                MessageBox.Show("导出失败");
                Logger.Error("导出失败: ",ex);
            }

        }

        public async Task ExportExcel(string addr = "d:\\test.xlsx") {
            await Task.Run(() => {
                ExcelPackage.License.SetNonCommercialPersonal("weikai");
                FileInfo newFile = new FileInfo(@addr);
                if (newFile.Exists) {
                    newFile.Delete();
                    newFile = new FileInfo(@addr);
                }
                using (ExcelPackage package = new ExcelPackage(newFile)) {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");//sheet的名字

                    worksheet.Cells[1, 1].Value = "Id";
                    worksheet.Cells[1, 2].Value = "EmployeeId";
                    worksheet.Cells[1, 3].Value = "Name";
                    worksheet.Cells[1, 4].Value = "Age";
                    worksheet.Cells[1, 5].Value = "Position";
                    worksheet.Cells[1, 6].Value = "Phone";

                    int count = _SummaryTable.Count;
                    int j = 0;
                    for (int i = 2; i <= count; i++) {
                        worksheet.Cells[i, 1].Value = _SummaryTable[j].Id;
                        worksheet.Cells[i, 2].Value = _SummaryTable[j].EmployeeId;
                        worksheet.Cells[i, 3].Value = _SummaryTable[j].Name;
                        worksheet.Cells[i, 4].Value = _SummaryTable[j].Age;
                        worksheet.Cells[i, 5].Value = _SummaryTable[j].Position;
                        worksheet.Cells[i, 6].Value = _SummaryTable[j].Phone;
                        ++j;
                    }
                    package.Save();
                    Logger.Warn("导出成功 ");
                    MessageBox.Show("保存成功");
                }
            });
        }



        //更新员工信息
        private void UpdateStaff(int? id) {
            //使用字典传输数据
            DialogParameters paras = new DialogParameters();//这是一个字典
            paras.Add("id", id);
            paras.Add("Title", "修改员工信息");//给对话框传数据

            //对话框服务,callback接收返回的参数
            DialogService.ShowDialog("UpdateStaffView", paras,
                callback => {
                    if (callback.Result == ButtonResult.OK) {
                        MessageBox.Show("修改成功");
                        //需要刷新列表
                        //RefreshStaff();
                        Application.Current.Dispatcher.BeginInvoke(RefreshStaff);
                    }
                    if (callback.Result == ButtonResult.No) {
                        MessageBox.Show("修改失败");
                    }
                });


        }

        //添加员工
        private void AddStaff() {
            //使用字典传输数据
            DialogParameters paras = new DialogParameters();//这是一个字典
            paras.Add("Title", "添加新员工");//给对话框传数据
            //对话框服务,callback接收返回的参数
            DialogService.ShowDialog("AddStaffView", paras,
                callback => {
                    if (callback.Result == ButtonResult.OK) {
                        //MessageBox.Show("添加成功");
                        //需要刷新列表
                        Application.Current.Dispatcher.BeginInvoke(RefreshStaff);
                    }
                    if (callback.Result == ButtonResult.No) {
                        //MessageBox.Show("添加失败");
                    }
                });
        }

        #endregion


        #region 属性
        //页码,默认为1
        private int _PageIndex = 1;

        public int PageIndex {
            get { return _PageIndex; }
            set {
                _PageIndex = value;
                RaisePropertyChanged();
            }
        }
        //总数据
        private ObservableCollection<StaffDetails> _SummaryTable;

        public ObservableCollection<StaffDetails> SummaryTable {
            get { return _SummaryTable; }
            set { _SummaryTable = value; RaisePropertyChanged(); }
        }
        //当前数据
        private ObservableCollection<StaffDetails> _CurrentDataList;

        public ObservableCollection<StaffDetails> CurrentDataList {
            get { return _CurrentDataList; }
            set {
                _CurrentDataList = value;
                RaisePropertyChanged();
            }
        }
        //最大页数
        private int _MaxPageCount = 10;

        public int MaxPageCount {
            get { return _MaxPageCount; }
            set {
                _MaxPageCount = value;
                RaisePropertyChanged();
            }
        }
        //每页大小:多少条数据
        private int _PageSize = 20;

        public int PageSize {
            get { return _PageSize; }
            set {
                _PageSize = value;
                RaisePropertyChanged();
            }
        }
        #endregion

    }
}
